/*
 * $Id: tty.c 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
 *
 * Copyright (c) 2006, 2007, 2008 Prabhu Gurumurthy <pgurumur@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "sshc.h"

char *
read_pass(const char *Prompt)
{
   logit(0, "in %s", __func__);
   return getpass(Prompt);
}

void
ssh_getty(const char *file, const int sendout)
{
   int rc = 0;
   logit(0, "in %s", __func__);

   logit(0, "requesting %s terminal", DEF_TERM);
   sshc->channel = libssh2_channel_open_session(sshc->session);
   if (!sshc->channel)
      error(0, "libssh2_channel_open_session()");

   assert(sshc->channel);

   rc = libssh2_channel_request_pty(sshc->channel, DEF_TERM);
   if (rc)
      error(0, "libssh2_channel_request_pty(): %s", ssh_geterror());

   logit(0, "requesting shell");
   if (libssh2_channel_shell(sshc->channel))
      error(0, "libssh2_channel_shell()");

   logit(0, "libssh2_channel_shell");

   got_channel = 1;

   char buffer[MAXLINE];
   memset(buffer, '\0', MAXLINE);
   int running = 1;
   FILE *stream = NULL;

   if (file) {
      sshc->input = fopen(file, "r");
      if (sshc->input == NULL)
         error(1, "fopen(%s)", file);

      stream = sshc->input;
   }
   else 
      stream = stdin;

   logit(0, "sending output to %d", sendout);
   logit(0, "using input fd: %d", fileno(stream));

   libssh2_channel_set_blocking(sshc->channel, 0);
   blocking(fileno(stream), 0);

   int offset = 0;

   errno = 0;
   do {
      int retval = ssh_read(sshc->sock, fileno(stdout), offset);
      if (wait_fd(sshc->sock, 0))
         continue;
      if (retval == 0) {
         if (wait_fd(fileno(stream), 1)) {
            retval = ssh_write(sshc->sock, fileno(stream));
            if (retval > 0) 
               ssh_send_eof();
            else
               offset = retval;
         }
      }

      if (errno == EAGAIN) 
         continue;
      else {
         int wc = libssh2_channel_wait_closed(sshc->channel);
         if (wc == 0)
            running = 0;
      }

   } while (running);

   blocking(fileno(stream), 1);
   logit(0, "done with %s", __func__);
}
